//
//  RepairHistoryDetailViewController.m
//  wtshoppingcite
//
//  Created by Baojia-LC on 14/11/13.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "RepairHistoryDetailViewController.h"
#import "RepairEditAndAddViewController.h"
#import "NetServiseCommonData.h"
#import "RepairHistoryDetailHeaderCell.h"
#import "RepairHistoryProcessCell.h"
#import "RepairDetailModel.h"
#import "ImgScrollView.h"
#import "FeeDetailCell.h"
#import "PariseCell.h"

@interface RepairHistoryDetailViewController ()<UITableViewDataSource,UITableViewDelegate,ImgScrollViewDelegate,RepairHistoryDetailDelegate>

@property(nonatomic,strong)UITableView* tableView;
@property(nonatomic,strong)NSDictionary* infoData;
@property(nonatomic,strong)NSString* status;
@property(nonatomic,strong)NSMutableArray* dataArray;
@property(nonatomic,strong)NSDictionary* repairs;
@property(nonatomic,strong)NSDictionary* payment;
@property(nonatomic,strong)NSMutableArray *stepArray;
@property(nonatomic,strong)NSString *complaint;
@property(nonatomic,strong)NSDictionary* complaintDic;

@property(strong,nonatomic)UIScrollView *myScrollView;
@property(strong,nonatomic)UIView *markView;
@property(strong,nonatomic)UIView *scrollPanel;
@property(strong,nonatomic)ImgScrollView *lastImgScrollView;
@property(assign,nonatomic)NSInteger currentIndex;

@end

@implementation RepairHistoryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    _scrollPanel = [[UIView alloc] initWithFrame:self.view.bounds];
    _scrollPanel.backgroundColor = [UIColor clearColor];
    _scrollPanel.alpha = 0;
    [self.view addSubview:_scrollPanel];
    
    _markView = [[UIView alloc] initWithFrame:_scrollPanel.bounds];
    _markView.backgroundColor = MAIN_BLACK_COLOR;
    _markView.alpha = 0.0;
    [_scrollPanel addSubview:_markView];
    
    _myScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [_scrollPanel addSubview:_myScrollView];
    _myScrollView.pagingEnabled = YES;
    _myScrollView.delegate = self;
    CGSize contentSize = _myScrollView.contentSize;
    contentSize.height = self.view.bounds.size.height;
    contentSize.width = 320 * 3;
    _myScrollView.contentSize = contentSize;

    
    _stepArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    if (_type == NSBlueViewControllerRepairStyle ) {
        [self setTitleView:@"报修记录详情"];
        [self setRightButton:@"报修" sel:@selector(repairClick:) viewController:self];
        [self getRepairDetail];

    }else if (_type == NSBlueViewControllerComplainStyle){
        [self setTitleView:@"投诉记录详情"];
        [self setRightButton:@"投诉" sel:@selector(repairClick:) viewController:self];
        [self getComplaintDetail];
    }
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
}


#pragma mark tableDelegate & tableDataSourse

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_type == NSBlueViewControllerRepairStyle){
        return 4;
    }else if (_type == NSBlueViewControllerComplationStyle){
        return 2;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(section == 0){
        return 1;
    }else if(section  == 1){
        
        if ([_stepArray isEqual:@""] ||_stepArray == nil){
            return 0;
        }else {
            if(_stepArray.count <=2){
                
                return _stepArray.count;
            
            }else{
                return 3;
            }
        }
    }else if (section == 2){
        return 1;
    }else if (section == 3){
        return 1;
    }
    return 0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    switch (indexPath.section) {
        case 0:
        {
            static NSString* CellIdentifier = @"cell";
            
            RepairHistoryDetailHeaderCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[RepairHistoryDetailHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate = self;
            }
            if (_type == NSBlueViewControllerRepairStyle) {
                
                if (_stepArray.count != 0) {
                    cell.state = self.state;
                }
                cell.repairs = _repairs;
                
            }else if (_type == NSBlueViewControllerComplainStyle){
                
                if (_stepArray.count != 0) {
                    cell.state = self.state;
                }
                cell.complaint = _complaintDic;
            }
            
            
            return cell;
            
        }break;
        case 1:{
            static NSString* CellIdentifier = @"myCell";
            
            RepairHistoryProcessCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[RepairHistoryProcessCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            if (_stepArray.count != 0) {
                cell.steps = _stepArray[indexPath.row];
            }
            return cell;
        }break;
        case 2:{
            static NSString* CellIdentifier = @"feeCell";
            
            FeeDetailCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[FeeDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.payment = _payment;
            return cell;
        }break;
        case 3:{
            static NSString* CellIdentifier = @"PariseCell";
            
                       
            PariseCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[PariseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.repairs = self.repairs;
            return cell;
        }break;
        default:
            break;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        
        switch (indexPath.section) {
            case 0:
            {
                if([self.state  isEqual: @"3"]){
                    return 300+60;
                }else{
                    return 150+60;
                }
            }break;
            case 1:{
                
                return 100;
            }break;
            case 2:{
                
                return 100;
            }break;
            case 3:{
                
                return 140;
            }break;
            default:
                break;
        }
    
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 3) {
         return 20;
    }
    return 1;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    view.backgroundColor = COLOR_RGB(238, 238, 238);
    
    UILabel* label = [self createLabelWithFrame:CGRectMake(15, -5, SCREEN_WIDTH, 30) text:@"" font:15 textAli:NSTextAlignmentLeft textColor:MAIN_GRAY_COLOR];
    [view addSubview:label];
    
    if(section == 0){
        if (_type == NSBlueViewControllerRepairStyle) {
            NSString* code = [NSString stringWithFormat:@"单号:%@",self.repairsId];
             label.text = code;
        }else if (_type == NSBlueViewControllerComplainStyle){
            NSString* code = [NSString stringWithFormat:@"单号:%@",self.complaintId];
            label.text = code;
        }
       
    }else if(section == 1){
        label.text = @"报修受理进程";
    }else if (section == 2){
        label.text = @"费用详情";
    }else if (section == 3){
        label.text = @"评价";
    }

    return view;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    view.backgroundColor = COLOR_RGB(238, 238, 238);
    
    UILabel* label = [self createLabelWithFrame:CGRectMake(15, -5, SCREEN_WIDTH, 30) text:@"" font:15 textAli:NSTextAlignmentLeft textColor:MAIN_GRAY_COLOR];
    [view addSubview:label];
    if (section == 3) {
        label.text = @"维修员信息";
    }
    return view;
}

#pragma mark 物业报修详情
-(void)getRepairDetail{
    
   
    
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
    SetValueForKey(listDic, self.repairsId, @"repairsId");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kRepairsDetail
                             andHttpMethod:@"POST"
                             andParameters:listDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                       
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                              [_stepArray removeAllObjects];
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSDictionary *repairs = [responseDic objectForKey:@"repairs"];
                             NSArray *steps = [responseDic objectForKey:@"steps"];
                             NSDictionary *payment = [responseDic objectForKey:@"payment"];
                             
                             _payment = payment;
                             _repairs = repairs;
                             
                             for (NSDictionary *dic in steps) {
                                 RepairDetailModel *repairDetailModel = [[RepairDetailModel alloc]initWithRepairDetailList:dic];
                                 
                                 [_stepArray addObject:repairDetailModel];
                             }
                             
                             [_tableView reloadData];
                         }
                      }];
    
}

#pragma mark 物业投诉详情
-(void)getComplaintDetail{
    
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
    SetValueForKey(listDic, self.complaintId, @"complaintId");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kComplaintDetail
                             andHttpMethod:@"POST"
                             andParameters:listDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             [_stepArray removeAllObjects];
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSDictionary *complaint = [responseDic objectForKey:@"complaint"];
                             NSArray *steps = [responseDic objectForKey:@"steps"];
                             _complaintDic = complaint;
                             
                             for (NSDictionary *dic in steps) {
                                 RepairDetailModel *repairDetailModel = [[RepairDetailModel alloc]initWithRepairDetailList:dic];
                                 
                                 [_stepArray addObject:repairDetailModel];

                             }
                             
                             
                             [_tableView reloadData];
                         }
                     }];

}

-(void)repairClick:(UIButton*)button{
    
    RepairEditAndAddViewController* repairEaVC = [[RepairEditAndAddViewController alloc] init];
    repairEaVC.hidesBottomBarWhenPushed = YES;
    repairEaVC.type = _type;
    [self.navigationController pushViewController:repairEaVC animated:YES];
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    ;
    
    if (_type == NSBlueViewControllerRepairStyle ) {
        [self getRepairDetail];
    }else if (_type == NSBlueViewControllerComplainStyle){
        [self getComplaintDetail];
    }
}


#pragma arguments 图片缩放delegate
-(void)tappedWithObject:(id)sender{
    
    [self.view bringSubviewToFront:_scrollPanel];
    _scrollPanel.alpha = 1.0;
    
    TapImageView *tmpView = sender;
    _currentIndex = tmpView.tag - 10000;
    
    
    //转换后的rect
    CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
    
    CGPoint contentOffset = _myScrollView.contentOffset;
    contentOffset.x = _currentIndex*320;
    _myScrollView.contentOffset = contentOffset;
    
    //添加
    [self addSubImgView];
    
    ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){contentOffset,_myScrollView.bounds.size}];
    [tmpImgScrollView setContentWithFrame:convertRect];
    [tmpImgScrollView setImage:tmpView.image];
    [_myScrollView addSubview:tmpImgScrollView];
    _myScrollView.contentSize = CGSizeMake(1*SCREEN_WIDTH, SCREEN_HEIGHT);
    
    tmpImgScrollView.i_delegate = self;
    
    [self performSelector:@selector(setOriginFrame:) withObject:tmpImgScrollView afterDelay:0.1];
    
}

#pragma mark - custom method 放大
- (void) addSubImgView
{
    
    for (UIView *tmpView in _myScrollView.subviews)
    {
        [tmpView removeFromSuperview];
    }
    
    for (int i = 0; i <= 1; i ++)
    {
        if (i == _currentIndex)
        {
            continue;
        }
        
        
//        NSLog(@"tmpView is image%@",tmpView.image);
        NSLog(@"%d",10000+i);
        
        TapImageView *tmpView = (TapImageView *)[self.view viewWithTag:10000+i];
        

        //转换后的rect
        CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
        
        ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){i*_myScrollView.bounds.size.width,0,_myScrollView.bounds.size}];
        [tmpImgScrollView setContentWithFrame:convertRect];
        [tmpImgScrollView setImage:tmpView.image];
        [_myScrollView addSubview:tmpImgScrollView];
        tmpImgScrollView.i_delegate = self;
        
        [tmpImgScrollView setAnimationRect];
    }
}


- (void) setOriginFrame:(ImgScrollView *) sender
{
    
    [UIView animateWithDuration:0.4 animations:^{
        [sender setAnimationRect];
        _markView.alpha = 1.0;
        [self.navigationController setNavigationBarHidden:YES];
    }];
}


#pragma mark 缩小
- (void) tapImageViewTappedWithObject:(id)sender
{
    [self.navigationController setNavigationBarHidden:NO];
    
    ImgScrollView *tmpImgView = sender;
    [UIView animateWithDuration:0.5 animations:^{
        _markView.alpha = 0;
        [tmpImgView rechangeInitRdct];
    } completion:^(BOOL finished) {
        _scrollPanel.alpha = 0;
    }];
    
}


#pragma mark - scroll delegate
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    _currentIndex = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
